using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace System;

public static class MulticastDelegateExtensions
{
    /// <summary>
    /// 按顺序调用给定 <see cref="MulticastDelegate"/> 中的所有异步委托。
    /// </summary>
    /// <typeparam name="TDelegate">给定 <see cref="MulticastDelegate"/> 中委托的类型。</typeparam>
    /// <param name="delegateExecution">用于执行每个委托的函数。</param>
    /// <returns>当所有项完成时将完成的 <see cref="Task"/>。</returns>
    public static Task InvokeAsync<TDelegate>(
        this MulticastDelegate multicastDelegate,
        Func<TDelegate, Task> delegateExecution)
        where TDelegate : Delegate =>
        multicastDelegate == null
            ? Task.CompletedTask
            : multicastDelegate.GetInvocationList()
                .Cast<TDelegate>()
                .AwaitEachAsync(delegateExecution);
}
